package com.leaves.common.util.docutil;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author LEAVES
 * @Version 1.0
 * @Date 2023年07日26 23时17分39秒
 * @Description: EXCEL模板写入
 */
public class ExcelTemplateWriter {

    public static void main(String[] args) {
        String templatePath = "D:\\Program Files (x86)\\app\\IDEA\\IDEA_WORKE\\sa-token-demo\\src\\main\\resources\\templates\\templates/三检表.xlsx";
        String outputPath = "D:\\Program Files (x86)\\app\\IDEA\\IDEA_WORKE\\sa-token-demo\\src\\main\\resources\\templates/result/三检表.xlsx";
        String imagePath = "D:\\Program Files (x86)\\app\\IDEA\\IDEA_WORKE\\sa-token-demo\\src\\main\\resources\\templates\\templates\\hyaqweb.jpg";

        try {
            // 使用ClassLoader加载资源文件
            //ClassLoader classLoader = ResourceFileExample.class.getClassLoader();

            // 读取模板文件
            FileInputStream inputStream = new FileInputStream(templatePath);
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);

            // 获取第一个工作表
            XSSFSheet sheet = workbook.getSheetAt(0);

            // 替换文本
            //replaceText(sheet, "${placeholder}", replacementText);
            xlxsReplaceText(sheet);

            // 插入图片
            insertImage(workbook, sheet, imagePath, 21, 3);

            // 保存输出文件
            FileOutputStream outputStream = new FileOutputStream(outputPath);
            workbook.write(outputStream);

            // 关闭流
            outputStream.close();
            inputStream.close();
            workbook.close();

            System.out.println("操作完成！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void xlxsReplaceText(Sheet sheet) {
        //xlsxData = new XlsxData();
        //xlsxData.setPlanName("测试计划");
        //xlsxData.setTankCarNumber("陕AA789Q");
        //xlsxData.setTankCarNumber("陕AA789Q");
        //xlsxData.setATime("2023-07-26 23:28");

        Map<String, String> map = new HashMap<>();
        map.put("${planName}", "测试计划");
        map.put("${tractorNumber}", "陕AA789Q");
        map.put("${tankCarNumber}", "陕AA789Q");
        map.put("${aTime}", "2023-07-26 23:28");
        map.put("${a1}", "√");
        map.put("${a2}", "×");
        map.put("${a3}", "√");
        map.put("${a4}", "☑");
        map.put("${a5}", "□");
        replaceText(sheet, map);
    }

    private static void replaceText(Sheet sheet, String findText, String replaceText) {
        for (Row row : sheet) {
            for (Cell cell : row) {
                if (cell.getCellType() == CellType.STRING) {
                    String cellValue = cell.getStringCellValue();
                    if (cellValue.contains(findText)) {
                        cellValue = cellValue.replace(findText, replaceText);
                        cell.setCellValue(cellValue);
                    }
                }
            }
        }
    }

    private static void replaceText(Sheet sheet, Map<String, String> map) {
        for (Row row : sheet) {
            for (Cell cell : row) {
                if (cell.getCellType() == CellType.STRING) {
                    String cellValue = cell.getStringCellValue();
                    for (String key : map.keySet()) {
                        if (cellValue.contains(key)) {
                            String value = map.get(key);
                            cellValue = cellValue.replace(key, value);
                            cell.setCellValue(cellValue);
                        }
                    }

                }
            }
        }
    }

    private static void insertImage(Workbook workbook, Sheet sheet, String imagePath) {
        try {
            InputStream imageStream = new FileInputStream(imagePath);
            byte[] imageBytes = readAllBytes(imageStream);
            imageStream.close();

            int pictureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
            CreationHelper helper = workbook.getCreationHelper();
            Drawing<?> drawing = sheet.createDrawingPatriarch();

            ClientAnchor anchor = helper.createClientAnchor();
            anchor.setCol1(1); // 图片所在列
            anchor.setRow1(1); // 图片所在行

            Picture picture = drawing.createPicture(anchor, pictureIdx);
            picture.resize(); // 自适应图片大小
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 插入图片
     *
     * @param workbook  工作簿
     * @param sheet     第几个sheet
     * @param imagePath 图片地址
     * @param line      图片所在行
     * @param row       图片所在列
     */
    private static void insertImage(Workbook workbook, Sheet sheet, String imagePath, int line, int row) {
        try {
            InputStream imageStream = new FileInputStream(imagePath);
            byte[] imageBytes = readAllBytes(imageStream);
            imageStream.close();

            int pictureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
            CreationHelper helper = workbook.getCreationHelper();
            Drawing<?> drawing = sheet.createDrawingPatriarch();

            ClientAnchor anchor = helper.createClientAnchor();
            anchor.setRow1(line); // 图片所在行
            anchor.setCol1(row); // 图片所在列

            Picture picture = drawing.createPicture(anchor, pictureIdx);
            picture.resize(0.5,1); // 指定图片图片大小
            // 获取单元格样式
            CellStyle cellStyle = workbook.createCellStyle();

            // 设置水平居中对齐
            cellStyle.setAlignment(HorizontalAlignment.CENTER);

            // 设置垂直居中对齐
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 获取要设置样式的单元格
            Cell cell = sheet.getRow(line).getCell(row); // 第2行第2列的单元格

            // 应用样式到单元格
            cell.setCellStyle(cellStyle);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static byte[] readAllBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        return outputStream.toByteArray();
    }

}

